import datetime
import json
import os

from django.http import HttpResponse
from django.shortcuts import render,render_to_response
from django.template.loader import render_to_string
from django.views import View
from Common import Fession_mini
from JobData.lagou import lagou_main
from JobData.Job51_shezhao import spider_main
from AdminTargetManage.TargetManageControl import getRule
# Create your views here.
def toPing():
    exit_code = os.system('ping www.baidu.com>con')
    if exit_code:
        return -1
    else:
        return 1
def GainRule(request):
    if request.method == "POST":
        data = {'ruleId': 1, 'web_Name': 'fangzhen', 'entrance_URL': 'http://search.51job.com/list/000000,000000,0100,01,9,99,%2B,2,1.html?lang=c&stype=1&postchannel=0000&workyear=99&cotype=99&degreefrom=99&jobterm=99&companysize=99&lonlat=0%2C0&radius=-1&ord_field=0&confirmdate=9&fromType=&dibiaoid=0&address=&line=&specialarea=00&from=&welfare=', 'execute_Script': 'Job51_shezhao/spider_main.py', 'storage_Table': 'data_51job_she', 'time_Week': '3-7', 'time_Day_start': '1:00', 'time_Day_end': '24:59', 'set_Time': datetime.datetime(2016, 11, 15, 10, 49), 'limit_Type': '1', 'limit_Value': '10', 'remark': '上次爬取时间：2019/5/20'}
        getRule.getRule().setOnerule(data)
        print("测试以细致连通性！！！！！！！！！！！")
    allRule =getRule.getRule().getAllrule()
    return render_to_response('GainRule.html',{'allRule':allRule})
def TurnOn(request):
    return render_to_response('404.html')

def reRule_lagou(request):
    if request.method == "POST":
        lagou_scope = lagou_main.SpiderMain()
        lagou_scope.craw('https://www.lagou.com/zhaopin/')
def reRule_51job(request):
    if request.method == "POST":
        if toPing() < 0:
            return HttpResponse("-1")
        elif toPing() > 0:
            spider_main.SpiderMain().craw('http://search.51job.com/list/000000,000000,0100,01,9,99,%2B,2,1.html?lang=c&stype=1&postchannel=0000&workyear=99&cotype=99&degreefrom=99&jobterm=99&companysize=99&lonlat=0%2C0&radius=-1&ord_field=0&confirmdate=9&fromType=&dibiaoid=0&address=&line=&specialarea=00&from=&welfare=')


class reRule_return(View):
    def __init__(self):
        self.job51_scope = spider_main.SpiderMain()
    def post(self,request):
        if request.POST.get('hidden_target_name') == 'lagou':
            print("\033[0;31m%s\033[0m" % "post方法成功，yeah！！")
            lagou_scope = lagou_main.SpiderMain()
            lagou_scope.craw('https://www.lagou.com/zhaopin/')
            return HttpResponse(json.dumps(200))
        if request.POST.get('hidden_target_name') == '51job':
            print("\033[0;31m%s\033[0m" % "post方法成功，yeah！！")
            return HttpResponse(json.dumps(200))
    def get(self,request):
        if request.GET.get('key') == 'lagou':
            _min=1
            _max=10
            # print(lagou_main.SpiderMain().get_data(min,max),'\n',time.ctime(time.time()))
            return HttpResponse(json.dumps(lagou_main.SpiderMain().get_data(_min, _max)))
        if request.GET.get('key') == '51job':
            if request.GET.get('operate') == 'start':
                print(toPing())
                if toPing() < 0:
                    return HttpResponse("-1")
                elif toPing() > 0:
                    self.job51_scope.craw('http://search.51job.com/list/000000,000000,0100,01,9,99,%2B,2,1.html?lang=c&stype=1&postchannel=0000&workyear=99&cotype=99&degreefrom=99&jobterm=99&companysize=99&lonlat=0%2C0&radius=-1&ord_field=0&confirmdate=9&fromType=&dibiaoid=0&address=&line=&specialarea=00&from=&welfare=')
            if request.GET.get('operate') == 'refresh':
                # print("\033[0;31m%s\033[0m" % json.dumps(Fession_mini.getFessionMini('nowAllDataText')))
                nowAllDataText = Fession_mini.getFessionMini('nowAllDataText')
                return HttpResponse(json.dumps(Fession_mini.getFessionMini('nowAllDataText')))
                # min = 1
                # max = 10
                # print(self.job51_scope.get_data(min, max), '\n', time.ctime(time.time()))
                # return HttpResponse(json.dumps(self.job51_scope.get_data(min, max)))
            if request.GET.get('operate') == 'cease':
                print("\033[0;31m%s\033[0m" % "我在view进行停止，yeah！！")
                Fession_mini.setFessionMini('self.cease',-1)
                print("\033[0;31m%s\033[0m" % "我就不信了"+str(Fession_mini.getFessionMini('self.cease')))
                return HttpResponse(200)
            elif request.GET.get('operate') == 'interrupt':
                print("\033[0;31m%s\033[0m" % "我在view进行中断，yeah！！")
                Fession_mini.setFessionMini('self.interrupt', int(request.GET.get('status')))
                print("\033[0;31m%s\033[0m" % "我就不信了sdfSDF"+str(Fession_mini.getFessionMini('self.interrupt')))
            elif request.GET.get('operate') == 'chart':
                sum = 0
                up = 0
                data = {}
                chart_date = []
                chart_data = []
                if Fession_mini.hasInAndNN('nowAllDataText') and Fession_mini.hasInAndNN('consume_time'):
                    nowAllDataText = Fession_mini.getFessionMini('nowAllDataText')
                    consume_time = Fession_mini.getFessionMini('consume_time')
                    # self_thisStrList = Fession_mini.getFessionMini('self.thisStrList')
                    # self_totalStrSum = Fession_mini.getFessionMini('self.totalStrSum')
                    # 时间
                    for i in range(len(consume_time)):
                        chart_data.append(consume_time[i])
                        chart_date.append(i)

                    # for v in consume_time:
                    #     sum += v
                    # for i in range(sum + 1):
                    #     chart_data.append(0)
                    #     chart_date.append(i)
                    # up = 0
                    # for i in consume_time:
                    #     index = i + up
                    #     up = index
                    #     chart_data[index] = 1
                    data['chart_data']=chart_data
                    data['chart_date']=chart_date
                    # data['yAxisMan'] = round(max(chart_data))
                    data['yAxisMin'] = Fession_mini.getFessionMini('type1pageCT')
                    data['self_thisStrList'] = Fession_mini.getFessionMini('self.thisStrList')
                    data['self_totalStrSum'] = Fession_mini.getFessionMini('self.totalStrSum')
                    print('我在测试测试测试呢！！',data)
                return HttpResponse(json.dumps(data))